// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ObjUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.RawMaterials;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.BrandMapper;
import com.fowo.api.mapper.ClassifyMapper;
import com.fowo.api.mapper.ProductCustomsPriceMapper;
import com.fowo.api.mapper.ProductGroupMapper;
import com.fowo.api.mapper.ProductIngredientsMapper;
import com.fowo.api.mapper.ProductInventoryMapper;
import com.fowo.api.mapper.ProductPackMapper;
import com.fowo.api.mapper.ProductQualityCheckMapper;
import com.fowo.api.mapper.ProductSupplierQuoteMapper;
import com.fowo.api.mapper.RawMaterialsMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.brand.BrandItemVo;
import com.fowo.api.model.brand.BrandSearchParamPo;
import com.fowo.api.model.classify.ClassifyItemVo;
import com.fowo.api.model.classify.ClassifySearchParamPo;
import com.fowo.api.model.product.customs.price.ProductCustomsPriceSearchParamPo;
import com.fowo.api.model.product.group.ProductGroupItemVo;
import com.fowo.api.model.product.group.ProductGroupSearchParamPo;
import com.fowo.api.model.product.ingredients.ProductIngredientsSearchParamPo;
import com.fowo.api.model.product.inventory.ProductInventorySearchParamPo;
import com.fowo.api.model.product.pack.ProductPackSearchParamPo;
import com.fowo.api.model.product.quality.check.ProductQualityCheckSearchParamPo;
import com.fowo.api.model.product.supplier.quote.ProductSupplierQuoteSearchParamPo;
import com.fowo.api.model.raw.materials.RawMaterialsExcelPo;
import com.fowo.api.model.raw.materials.RawMaterialsImportPo;
import com.fowo.api.model.raw.materials.RawMaterialsItemVo;
import com.fowo.api.model.raw.materials.RawMaterialsSearchParamPo;
import com.fowo.api.model.raw.materials.RawMaterialsVo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.ProductCustomsPriceService;
import com.fowo.api.service.ProductIngredientsService;
import com.fowo.api.service.ProductInventoryService;
import com.fowo.api.service.ProductPackService;
import com.fowo.api.service.ProductQualityCheckService;
import com.fowo.api.service.ProductSupplierQuoteService;
import com.fowo.api.service.RawMaterialsService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 原材料管理 服务实现基类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，沈友谅
 */
@Slf4j
@DataObjectType(RawMaterials.class)
@DS("ds24")
public class RawMaterialsBaseServiceImpl
  extends ServiceImpl<RawMaterialsMapper, RawMaterials>
  implements RawMaterialsService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("groupName", "pg.`name`");
      put("classifyName", "c.`name`");
      put("brandName", "b.`name`");
      put("developerName", "su.`name`");
      put("principalName", "su2.`name`");
      put("buyerName", "su3.`name`");
      put("defaultWarehouseName", "w.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected RawMaterialsService self;

  @Resource
  protected ProductSupplierQuoteService productSupplierQuoteService;

  @Resource
  protected ProductIngredientsService productIngredientsService;

  @Resource
  protected ProductPackService productPackService;

  @Resource
  protected ProductCustomsPriceService productCustomsPriceService;

  @Resource
  protected ProductQualityCheckService productQualityCheckService;

  @Resource
  protected ProductInventoryService productInventoryService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ProductGroupMapper productGroupMapper;

  @Resource
  protected ClassifyMapper classifyMapper;

  @Resource
  protected BrandMapper brandMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建原材料管理
   * @param model 原材料管理
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(RawMaterialsVo model) throws Exception {
    saveIdentityCheck(model, null);
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    RawMaterials entity = new RawMaterials();
    BeanUtils.copyProperties(model, entity);
    // 设置常量字段
    entity.setType("CP02");
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("原材料管理保存失败");
  }

  /**
   * 更新所有子表
   * @param model 原材料管理
   */
  protected void updateAllChilds(RawMaterialsVo model) throws Exception {
    if (model.getProductSupplierQuote() != null) {
      productSupplierQuoteService.saveAllByParentProduct(
        model.getId(),
        model.getProductSupplierQuote()
      );
    }

    if (model.getIngredients() != null) {
      productIngredientsService.saveAllByProductId(
        model.getId(),
        model.getIngredients()
      );
    }

    if (model.getPacks() != null) {
      productPackService.saveAllByProductId(model.getId(), model.getPacks());
    }

    if (model.getCustoms() != null) {
      productCustomsPriceService.saveAllByProductId(
        model.getId(),
        model.getCustoms()
      );
    }

    if (model.getChecks() != null) {
      productQualityCheckService.saveAllByProductId(
        model.getId(),
        model.getChecks()
      );
    }

    if (model.getInventorys() != null) {
      productInventoryService.saveAllByItemId(
        model.getId(),
        model.getInventorys()
      );
    }
  }

  /**
   * 更新原材料管理
   * @param model 原材料管理
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(RawMaterialsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    RawMaterials entity = this.getById(model.getId());
    if (entity == null || !Objects.equals(entity.getType(), "CP02")) {
      throw new Exception("原材料管理不存在");
    }
    saveIdentityCheck(model, entity);
    BeanUtils.copyProperties(
      model,
      entity,
      "lastUpdateUser",
      "lastUpdateTime",
      "createUser",
      "createTime",
      "id",
      "purchaseRecords",
      "inventorys"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新原材料管理（带空值）
   * @param model 原材料管理
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(RawMaterialsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    RawMaterials entity = this.getById(model.getId());
    if (entity == null || !Objects.equals(entity.getType(), "CP02")) {
      throw new Exception("原材料管理不存在");
    }
    saveIdentityCheck(model, entity);
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(RawMaterials::getName, model.getName())
      .set(RawMaterials::getSku, model.getSku())
      .set(RawMaterials::getGroup, model.getGroup())
      .set(RawMaterials::getModel, model.getModel())
      .set(RawMaterials::getUnit, model.getUnit())
      .set(RawMaterials::getSalesStatus, model.getSalesStatus())
      .set(RawMaterials::getClassify, model.getClassify())
      .set(RawMaterials::getBrand, model.getBrand())
      .set(RawMaterials::getDeveloper, model.getDeveloper())
      .set(RawMaterials::getPrincipal, model.getPrincipal())
      .set(RawMaterials::getLabel, model.getLabel())
      .set(RawMaterials::getInfo1, model.getInfo1())
      .set(RawMaterials::getInfo2, model.getInfo2())
      .set(RawMaterials::getEpColor, model.getEpColor())
      .set(RawMaterials::getProductDescription, model.getProductDescription())
      .set(RawMaterials::getLastUpdateUser, model.getLastUpdateUser())
      .set(RawMaterials::getLastUpdateTime, model.getLastUpdateTime())
      .set(
        model.getAttachment() != null,
        RawMaterials::getAttachment,
        JSON.toJSONString(model.getAttachment())
      )
      .setSql(model.getAttachment() == null, "attachment = null")
      .eq(RawMaterials::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 唯一性检查
   * @param entity 要检查的数据
   * @param rawEntity 要检查的未变更前数据(新增时为 null)
   * @throws RException 不满足唯一性检查条件时触发
   */
  protected void saveIdentityCheck(RawMaterials entity, RawMaterials rawEntity)
    throws RException {
    if (
      baseMapper.exists(
        Wrappers
          .<RawMaterials>query()
          .ne(
            rawEntity != null,
            "id",
            rawEntity != null ? rawEntity.getId() : null
          )
          .ne(
            rawEntity == null && entity != null && entity.getId() != null,
            "id",
            entity.getId()
          )
          .eq("type", "CP02")
          .eq(
            "sku",
            entity.getSku() == null && rawEntity != null
              ? rawEntity.getSku()
              : entity.getSku()
          )
      )
    ) {
      throw new RException("当前数据不满足“SKU”唯一要求");
    }
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(RawMaterialsSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 供应商报价(productSupplierQuote) 对应的对象
    ProductSupplierQuoteSearchParamPo productSupplierQuoteSearchParam =
      new ProductSupplierQuoteSearchParamPo();
    productSupplierQuoteSearchParam.setDisableDataPremissions(true);
    productSupplierQuoteSearchParam.setParentProductInList(ids);
    ProductSupplierQuoteMapper localProductSupplierQuoteMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductSupplierQuoteMapper.class);
    productSupplierQuoteSearchParam.applySqlSegments();
    List<Long> productSupplierQuoteIdList =
      localProductSupplierQuoteMapper.searchIds(
        productSupplierQuoteSearchParam
      );
    if (!productSupplierQuoteIdList.isEmpty()) {
      ProductSupplierQuoteService localProductSupplierQuoteService =
        ContextHolder
          .getApplicationContext()
          .getBean(ProductSupplierQuoteService.class);
      localProductSupplierQuoteService.batchDelete(productSupplierQuoteIdList);
    }

    // FIXME: 未找到子表字段 最近采购记录(purchaseRecords) 对应的对象，忽略删除处理！
    // 处理子表字段 辅料&包材(ingredients) 对应的对象
    ProductIngredientsSearchParamPo ingredientsSearchParam =
      new ProductIngredientsSearchParamPo();
    ingredientsSearchParam.setDisableDataPremissions(true);
    ingredientsSearchParam.setProductIdInList(ids);
    ProductIngredientsMapper localProductIngredientsMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductIngredientsMapper.class);
    ingredientsSearchParam.applySqlSegments();
    List<Long> ingredientsIdList = localProductIngredientsMapper.searchIds(
      ingredientsSearchParam
    );
    if (!ingredientsIdList.isEmpty()) {
      ProductIngredientsService localProductIngredientsService = ContextHolder
        .getApplicationContext()
        .getBean(ProductIngredientsService.class);
      localProductIngredientsService.batchDelete(ingredientsIdList);
    }

    // 处理子表字段 辅料&包材(可选)(packs) 对应的对象
    ProductPackSearchParamPo packsSearchParam = new ProductPackSearchParamPo();
    packsSearchParam.setDisableDataPremissions(true);
    packsSearchParam.setProductIdInList(ids);
    ProductPackMapper localProductPackMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductPackMapper.class);
    packsSearchParam.applySqlSegments();
    List<Long> packsIdList = localProductPackMapper.searchIds(packsSearchParam);
    if (!packsIdList.isEmpty()) {
      ProductPackService localProductPackService = ContextHolder
        .getApplicationContext()
        .getBean(ProductPackService.class);
      localProductPackService.batchDelete(packsIdList);
    }

    // 处理子表字段 报关清关费用(customs) 对应的对象
    ProductCustomsPriceSearchParamPo customsSearchParam =
      new ProductCustomsPriceSearchParamPo();
    customsSearchParam.setDisableDataPremissions(true);
    customsSearchParam.setProductIdInList(ids);
    ProductCustomsPriceMapper localProductCustomsPriceMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductCustomsPriceMapper.class);
    customsSearchParam.applySqlSegments();
    List<Long> customsIdList = localProductCustomsPriceMapper.searchIds(
      customsSearchParam
    );
    if (!customsIdList.isEmpty()) {
      ProductCustomsPriceService localProductCustomsPriceService = ContextHolder
        .getApplicationContext()
        .getBean(ProductCustomsPriceService.class);
      localProductCustomsPriceService.batchDelete(customsIdList);
    }

    // 处理子表字段 质检标准(checks) 对应的对象
    ProductQualityCheckSearchParamPo checksSearchParam =
      new ProductQualityCheckSearchParamPo();
    checksSearchParam.setDisableDataPremissions(true);
    checksSearchParam.setProductIdInList(ids);
    ProductQualityCheckMapper localProductQualityCheckMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductQualityCheckMapper.class);
    checksSearchParam.applySqlSegments();
    List<Long> checksIdList = localProductQualityCheckMapper.searchIds(
      checksSearchParam
    );
    if (!checksIdList.isEmpty()) {
      ProductQualityCheckService localProductQualityCheckService = ContextHolder
        .getApplicationContext()
        .getBean(ProductQualityCheckService.class);
      localProductQualityCheckService.batchDelete(checksIdList);
    }

    // 处理子表字段 库存情况(inventorys) 对应的对象
    ProductInventorySearchParamPo inventorysSearchParam =
      new ProductInventorySearchParamPo();
    inventorysSearchParam.setDisableDataPremissions(true);
    inventorysSearchParam.setItemIdInList(ids);
    ProductInventoryMapper localProductInventoryMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductInventoryMapper.class);
    inventorysSearchParam.applySqlSegments();
    List<Long> inventorysIdList = localProductInventoryMapper.searchIds(
      inventorysSearchParam
    );
    if (!inventorysIdList.isEmpty()) {
      ProductInventoryService localProductInventoryService = ContextHolder
        .getApplicationContext()
        .getBean(ProductInventoryService.class);
      localProductInventoryService.batchDelete(inventorysIdList);
    }
  }

  /**
   * 删除原材料管理
   * @param id 原材料管理的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除原材料管理
   * @param ids 原材料管理的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<RawMaterialsImportPo> excelToImportRow(
    RawMaterialsImportPo row,
    Integer rowNumber,
    RawMaterialsVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<RawMaterialsImportPo> ir = new ImportRow<RawMaterialsImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<RawMaterialsImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new RawMaterialsVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, RawMaterialsImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getSalesStatus())) {
      List<SysDictAllItem> salesStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "salesStatus",
          n -> sysDictService.getDictItems("SCM00006")
        );
      RawMaterialsVo finalVo = vo;
      salesStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSalesStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSalesStatus(i.getItemValue()),
          () ->
            ir.addError(
              "salesStatus",
              String.format(
                "必须为 %s 中之一",
                salesStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setPurchasingDeliveryTime(
      SheetUtils.tryToInteger(row.getPurchasingDeliveryTime())
    );
    vo.setProcurementCost(SheetUtils.tryToDecimal(row.getProcurementCost()));
    vo.setProductWidth(SheetUtils.tryToDecimal(row.getProductWidth()));
    vo.setProductNet(SheetUtils.tryToDecimal(row.getProductNet()));
    vo.setProductLength(SheetUtils.tryToDecimal(row.getProductLength()));
    vo.setProductHeight(SheetUtils.tryToDecimal(row.getProductHeight()));
    vo.setProductGross(SheetUtils.tryToDecimal(row.getProductGross()));
    vo.setBoxWidth(SheetUtils.tryToDecimal(row.getBoxWidth()));
    vo.setBoxLength(SheetUtils.tryToDecimal(row.getBoxLength()));
    vo.setBoxHeight(SheetUtils.tryToDecimal(row.getBoxHeight()));
    vo.setPackingWeight(SheetUtils.tryToDecimal(row.getPackingWeight()));
    vo.setPackingNum(SheetUtils.tryToInteger(row.getPackingNum()));
    vo.setPackageWidth(SheetUtils.tryToDecimal(row.getPackageWidth()));
    vo.setPackageLength(SheetUtils.tryToDecimal(row.getPackageLength()));
    vo.setPackageHeight(SheetUtils.tryToDecimal(row.getPackageHeight()));
    if (StringUtils.hasText(row.getLogisticsPriceType())) {
      List<SysDictAllItem> logisticsPriceTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsPriceType",
          n -> sysDictService.getDictItems("SCM00030")
        );
      RawMaterialsVo finalVo = vo;
      logisticsPriceTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getLogisticsPriceType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setLogisticsPriceType(i.getItemValue()),
          () ->
            ir.addError(
              "logisticsPriceType",
              String.format(
                "必须为 %s 中之一",
                logisticsPriceTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPurchasePriceType())) {
      List<SysDictAllItem> purchasePriceTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "purchasePriceType",
          n -> sysDictService.getDictItems("SCM00031")
        );
      RawMaterialsVo finalVo = vo;
      purchasePriceTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPurchasePriceType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPurchasePriceType(i.getItemValue()),
          () ->
            ir.addError(
              "purchasePriceType",
              String.format(
                "必须为 %s 中之一",
                purchasePriceTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPriceType())) {
      List<SysDictAllItem> priceTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "priceType",
          n -> sysDictService.getDictItems("SCM00032")
        );
      RawMaterialsVo finalVo = vo;
      priceTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPriceType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPriceType(i.getItemValue()),
          () ->
            ir.addError(
              "priceType",
              String.format(
                "必须为 %s 中之一",
                priceTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setCustomsCharges(SheetUtils.tryToDecimal(row.getCustomsCharges()));
    if (StringUtils.hasText(row.getCustomsCurrency())) {
      List<SysDictAllItem> customsCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      RawMaterialsVo finalVo = vo;
      customsCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "customsCurrency",
              String.format(
                "必须为 %s 中之一",
                customsCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getSpecialProperties())) {
      List<SysDictAllItem> specialPropertiesItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "specialProperties",
          n -> sysDictService.getDictItems("SCM00009")
        );
      RawMaterialsVo finalVo = vo;
      List<String> specialPropertiesTexts = Arrays
        .stream(row.getSpecialProperties().split(","))
        .filter(StringUtils::hasText)
        .collect(Collectors.toList());
      finalVo.setSpecialProperties(
        specialPropertiesItems
          .stream()
          .filter(i -> specialPropertiesTexts.contains(i.getItemText()))
          .map(SysDictAllItem::getItemValue)
          .collect(Collectors.joining(","))
      );
    }
    if (StringUtils.hasText(row.getCustomsDiscounts())) {
      List<SysDictAllItem> customsDiscountsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsDiscounts",
          n -> sysDictService.getDictItems("SCM00010")
        );
      RawMaterialsVo finalVo = vo;
      customsDiscountsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsDiscounts()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsDiscounts(i.getItemValue()),
          () ->
            ir.addError(
              "customsDiscounts",
              String.format(
                "必须为 %s 中之一",
                customsDiscountsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCustomsBrand())) {
      List<SysDictAllItem> customsBrandItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsBrand",
          n -> sysDictService.getDictItems("SCM00011")
        );
      RawMaterialsVo finalVo = vo;
      customsBrandItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsBrand()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsBrand(i.getItemValue()),
          () ->
            ir.addError(
              "customsBrand",
              String.format(
                "必须为 %s 中之一",
                customsBrandItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCustomsWeave())) {
      List<SysDictAllItem> customsWeaveItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsWeave",
          n -> sysDictService.getDictItems("SCM00012")
        );
      RawMaterialsVo finalVo = vo;
      customsWeaveItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsWeave()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsWeave(i.getItemValue()),
          () ->
            ir.addError(
              "customsWeave",
              String.format(
                "必须为 %s 中之一",
                customsWeaveItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCheckType())) {
      List<SysDictAllItem> checkTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "checkType",
          n -> sysDictService.getDictItems("SCM00013")
        );
      RawMaterialsVo finalVo = vo;
      checkTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCheckType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCheckType(i.getItemValue()),
          () ->
            ir.addError(
              "checkType",
              String.format(
                "必须为 %s 中之一",
                checkTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setIsBatch(SheetUtils.tryToBoolean(row.getIsBatch()));
    if (StringUtils.hasText(row.getPutaway())) {
      List<SysDictAllItem> putawayItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "putaway",
          n -> sysDictService.getDictItems("SCM00034")
        );
      RawMaterialsVo finalVo = vo;
      putawayItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPutaway()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPutaway(i.getItemValue()),
          () ->
            ir.addError(
              "putaway",
              String.format(
                "必须为 %s 中之一",
                putawayItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setStocktaking(SheetUtils.tryToInteger(row.getStocktaking()));
    if (StringUtils.hasText(row.getMetricOrBritish())) {
      List<SysDictAllItem> metricOrBritishItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "metricOrBritish",
          n -> sysDictService.getDictItems("SCM00007")
        );
      RawMaterialsVo finalVo = vo;
      metricOrBritishItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getMetricOrBritish()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setMetricOrBritish(i.getItemValue()),
          () ->
            ir.addError(
              "metricOrBritish",
              String.format(
                "必须为 %s 中之一",
                metricOrBritishItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00016")
        );
      RawMaterialsVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    // 处理关联字段“分组”
    if (
      !SheetUtils.isBlank(row.getGroupName()) &&
      SheetUtils.isBlank(row.getGroup())
    ) {
      ProductGroupSearchParamPo groupSearchParam =
        new ProductGroupSearchParamPo();
      groupSearchParam.setLimit(2); // 最大只返回二行记录
      groupSearchParam.setNameEq(SheetUtils.trim(row.getGroupName()));
      groupSearchParam.applySqlSegments();
      List<ProductGroupItemVo> groupMatches = productGroupMapper.search(
        groupSearchParam
      );
      if (groupMatches.size() == 0) {
        ir.addError("groupName", "未能在分组管理中找到匹配的数据");
      } else if (groupMatches.size() > 1) {
        ir.addError("groupName", "关联不唯一，在分组管理中找到多个匹配的数据");
      } else {
        vo.setGroup(groupMatches.get(0).getId());
      }
    }
    // 处理关联字段“分类”
    if (
      !SheetUtils.isBlank(row.getClassifyName()) &&
      SheetUtils.isBlank(row.getClassify())
    ) {
      ClassifySearchParamPo classifySearchParam = new ClassifySearchParamPo();
      classifySearchParam.setLimit(2); // 最大只返回二行记录
      classifySearchParam.setNameEq(SheetUtils.trim(row.getClassifyName()));
      classifySearchParam.applySqlSegments();
      List<ClassifyItemVo> classifyMatches = classifyMapper.search(
        classifySearchParam
      );
      if (classifyMatches.size() == 0) {
        ir.addError("classifyName", "未能在分类管理中找到匹配的数据");
      } else if (classifyMatches.size() > 1) {
        ir.addError(
          "classifyName",
          "关联不唯一，在分类管理中找到多个匹配的数据"
        );
      } else {
        vo.setClassify(classifyMatches.get(0).getId());
      }
    }
    // 处理关联字段“品牌”
    if (
      !SheetUtils.isBlank(row.getBrandName()) &&
      SheetUtils.isBlank(row.getBrand())
    ) {
      BrandSearchParamPo brandSearchParam = new BrandSearchParamPo();
      brandSearchParam.setLimit(2); // 最大只返回二行记录
      brandSearchParam.setNameEq(SheetUtils.trim(row.getBrandName()));
      brandSearchParam.applySqlSegments();
      List<BrandItemVo> brandMatches = brandMapper.search(brandSearchParam);
      if (brandMatches.size() == 0) {
        ir.addError("brandName", "未能在品牌管理中找到匹配的数据");
      } else if (brandMatches.size() > 1) {
        ir.addError("brandName", "关联不唯一，在品牌管理中找到多个匹配的数据");
      } else {
        vo.setBrand(brandMatches.get(0).getId());
      }
    }
    // 处理关联字段“开发人”
    if (
      !SheetUtils.isBlank(row.getDeveloperName()) &&
      SheetUtils.isBlank(row.getDeveloper())
    ) {
      SysUserSearch developerSearchParam = new SysUserSearch();
      developerSearchParam.setLimit(2); // 最大只返回二行记录
      developerSearchParam.setNameEq(SheetUtils.trim(row.getDeveloperName()));
      developerSearchParam.applySqlSegments();
      List<SysUserItemVo> developerMatches = sysUserMapper.search(
        developerSearchParam
      );
      if (developerMatches.size() == 0) {
        ir.addError("developerName", "未能在用户中找到匹配的数据");
      } else if (developerMatches.size() > 1) {
        ir.addError("developerName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setDeveloper(developerMatches.get(0).getId());
      }
    }
    // 处理关联字段“产品负责人”
    if (
      !SheetUtils.isBlank(row.getPrincipalName()) &&
      SheetUtils.isBlank(row.getPrincipal())
    ) {
      SysUserSearch principalSearchParam = new SysUserSearch();
      principalSearchParam.setLimit(2); // 最大只返回二行记录
      principalSearchParam.setNameEq(SheetUtils.trim(row.getPrincipalName()));
      principalSearchParam.applySqlSegments();
      List<SysUserItemVo> principalMatches = sysUserMapper.search(
        principalSearchParam
      );
      if (principalMatches.size() == 0) {
        ir.addError("principalName", "未能在用户中找到匹配的数据");
      } else if (principalMatches.size() > 1) {
        ir.addError("principalName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setPrincipal(principalMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购员”
    if (
      !SheetUtils.isBlank(row.getBuyerName()) &&
      SheetUtils.isBlank(row.getBuyer())
    ) {
      SysUserSearch buyerSearchParam = new SysUserSearch();
      buyerSearchParam.setLimit(2); // 最大只返回二行记录
      buyerSearchParam.setNameEq(SheetUtils.trim(row.getBuyerName()));
      buyerSearchParam.applySqlSegments();
      List<SysUserItemVo> buyerMatches = sysUserMapper.search(buyerSearchParam);
      if (buyerMatches.size() == 0) {
        ir.addError("buyerName", "未能在用户中找到匹配的数据");
      } else if (buyerMatches.size() > 1) {
        ir.addError("buyerName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setBuyer(buyerMatches.get(0).getId());
      }
    }
    // 处理关联字段“默认仓库”
    if (
      !SheetUtils.isBlank(row.getDefaultWarehouseName()) &&
      SheetUtils.isBlank(row.getDefaultWarehouse())
    ) {
      WarehouseSearchParamPo defaultWarehouseSearchParam =
        new WarehouseSearchParamPo();
      defaultWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      defaultWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getDefaultWarehouseName())
      );
      defaultWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> defaultWarehouseMatches = warehouseMapper.search(
        defaultWarehouseSearchParam
      );
      if (defaultWarehouseMatches.size() == 0) {
        ir.addError(
          "defaultWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (defaultWarehouseMatches.size() > 1) {
        ir.addError(
          "defaultWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDefaultWarehouse(defaultWarehouseMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<RawMaterialsImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<RawMaterialsImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            RawMaterialsImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              RawMaterialsImportPo row,
              AnalysisContext cxt
            ) {
              RawMaterialsVo vo = new RawMaterialsVo();
              ImportRow<RawMaterialsImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // 检查SKU唯一组
                RawMaterials existsObj = baseMapper.selectOne(
                  Wrappers
                    .<RawMaterials>query()
                    .eq("type", "CP02")
                    .eq("sku", vo.getSku())
                );
                if (existsObj != null) {
                  ir.setUpdateId(existsObj.getId());
                }
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<RawMaterialsImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<RawMaterialsImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      RawMaterialsVo vo = new RawMaterialsVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    RawMaterialsSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "group",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((RawMaterialsItemVo) r).getGroupName())
          )
      );
      exportOptions.addFieldMappingOption(
        "salesStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00006")
      );
      exportOptions.addFieldMappingOption(
        "classify",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((RawMaterialsItemVo) r).getClassifyName())
          )
      );
      exportOptions.addFieldMappingOption(
        "brand",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((RawMaterialsItemVo) r).getBrandName())
          )
      );
      exportOptions.addFieldMappingOption(
        "buyer",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((RawMaterialsItemVo) r).getBuyerName())
          )
      );
      exportOptions.addStringFields(
        "name",
        "sku",
        "groupName",
        "model",
        "unit",
        "salesStatus",
        "classifyName",
        "brandName",
        "info1",
        "info2",
        "epColor",
        "buyerName"
      );

      String fileName = String.format(
        "原材料管理(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> salesStatusItems = sysDictService.getDictItems(
      "SCM00006"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<RawMaterialsExcelPo> items = new ArrayList<RawMaterialsExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<RawMaterialsItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<RawMaterialsItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (RawMaterialsItemVo item : list) {
        RawMaterialsExcelPo excel = new RawMaterialsExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getSalesStatus() != null) {
          salesStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSalesStatus()))
            .findFirst()
            .ifPresent(i -> excel.setSalesStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "原材料管理(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(RawMaterialsExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过品名查询原材料管理主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByName(String name) {
    return this.baseMapper.getIdByName(name);
  }

  /**
   * 通过品名查询原材料管理多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByName(List<String> list) {
    return this.baseMapper.getIdsByName(list);
  }

  /**
   * 通过原材料管理主键查询品名
   */
  @Override
  public String getNameById(Long id) {
    return this.baseMapper.getNameById(id);
  }

  /**
   * 通过原材料管理主键查询品名列表
   */
  @Override
  public List<String> getNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("name"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 原材料管理的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public RawMaterialsVo getVoById(Long id) throws Exception {
    RawMaterialsVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    ProductSupplierQuoteSearchParamPo productSupplierQuoteSearchParamPo =
      new ProductSupplierQuoteSearchParamPo();
    productSupplierQuoteSearchParamPo.setParentProduct(id);
    productSupplierQuoteSearchParamPo.getExtendData().put("queryMode", "sub");
    productSupplierQuoteSearchParamPo
      .getExtendData()
      .put("queryParent", "RawMaterials");
    productSupplierQuoteSearchParamPo.applySqlSegments();
    vo.setProductSupplierQuote(
      productSupplierQuoteService.search(productSupplierQuoteSearchParamPo)
    );

    ProductIngredientsSearchParamPo ingredientsSearchParamPo =
      new ProductIngredientsSearchParamPo();
    ingredientsSearchParamPo.setProductId(id);
    ingredientsSearchParamPo.getExtendData().put("queryMode", "sub");
    ingredientsSearchParamPo.getExtendData().put("queryParent", "RawMaterials");
    ingredientsSearchParamPo.applySqlSegments();
    vo.setIngredients(
      productIngredientsService.search(ingredientsSearchParamPo)
    );

    ProductPackSearchParamPo packsSearchParamPo =
      new ProductPackSearchParamPo();
    packsSearchParamPo.setProductId(id);
    packsSearchParamPo.getExtendData().put("queryMode", "sub");
    packsSearchParamPo.getExtendData().put("queryParent", "RawMaterials");
    packsSearchParamPo.applySqlSegments();
    vo.setPacks(productPackService.search(packsSearchParamPo));

    ProductCustomsPriceSearchParamPo customsSearchParamPo =
      new ProductCustomsPriceSearchParamPo();
    customsSearchParamPo.setProductId(id);
    customsSearchParamPo.getExtendData().put("queryMode", "sub");
    customsSearchParamPo.getExtendData().put("queryParent", "RawMaterials");
    customsSearchParamPo.applySqlSegments();
    vo.setCustoms(productCustomsPriceService.search(customsSearchParamPo));

    ProductQualityCheckSearchParamPo checksSearchParamPo =
      new ProductQualityCheckSearchParamPo();
    checksSearchParamPo.setProductId(id);
    checksSearchParamPo.getExtendData().put("queryMode", "sub");
    checksSearchParamPo.getExtendData().put("queryParent", "RawMaterials");
    checksSearchParamPo.applySqlSegments();
    vo.setChecks(productQualityCheckService.search(checksSearchParamPo));

    ProductInventorySearchParamPo inventorysSearchParamPo =
      new ProductInventorySearchParamPo();
    inventorysSearchParamPo.setItemId(id);
    inventorysSearchParamPo.getExtendData().put("queryMode", "sub");
    inventorysSearchParamPo.getExtendData().put("queryParent", "RawMaterials");
    inventorysSearchParamPo.applySqlSegments();
    vo.setInventorys(productInventoryService.search(inventorysSearchParamPo));

    return vo;
  }

  /**
   * 分页查询原材料管理
   * @param search 查询条件
   * @return 原材料管理分页查询结果
   */
  @Override
  public Page<RawMaterialsItemVo> pageSearch(RawMaterialsSearchParamPo search) {
    Page<RawMaterialsItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(RawMaterialsItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 原材料管理快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'RawMaterialsOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<RawMaterialsItemVo>> searchOptions(
    RawMaterialsSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询原材料管理
   * @param search 查询条件
   * @return 原材料管理列表查询结果
   */
  @Override
  public List<RawMaterialsItemVo> search(RawMaterialsSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询原材料管理最后更新时间
   * @param search 查询条件
   * @return 原材料管理最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(RawMaterialsSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
